from rest_framework import serializers, status
from rest_framework.response import Response

from apps.spit.models import Spit


class SpitListSerializer(serializers.ModelSerializer):

    parent = serializers.PrimaryKeyRelatedField(required=False, queryset=Spit.objects.all())
    class Meta:
        model = Spit
        fields = '__all__'

    def create(self, validated_data):
        parent = validated_data.get('parent')
        if parent is None:
            spit = super().create(validated_data)
        else:
            try:
                user = self.context['request'].user
            except Exception:
                raise ValueError('用户未登录')
            else:
                spit = super().create(validated_data)
                spit.userid = str(user.id)
                spit.nickname = user.nickname or user.username
                spit.avatar = user.avatar
                spit.save()
                try:
                    cspit = Spit.objects.get(pk=parent.id)
                except Spit.DoesNotExist:
                    return Response(status=status.HTTP_400_BAD_REQUEST)
                else:
                    cspit.comment += 1
                    cspit.save()
        return spit


